package com.syxbyi._3tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;

/*
使用基于 tcp 协议的编程模型实现多人同时在线聊天，要求每个客户端将发 送的聊天内容发送到服务器，服务器接收到后转发给当前所有在线的客户端
 */
public class ChatServer {
    private ServerSocket socket;
    Map<Socket, User> clients;  // 记录socket和用户的对应关系，已关闭的socket会从表中删除

    public ChatServer() {
        clients = new HashMap<>();
        try {
            socket = new ServerSocket(6666);
            while (true) {
                // 每当总服务器接受到一个连接，就下发给一个线程来处理
                Socket s = socket.accept();
                new Thread(new ChatServerThread(this, s)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ChatServer server = new ChatServer();
    }
}
